<template>
  <div class="event-report-container">
    <div class="page-header">
      <h2>活动统计分析</h2>
      <div class="header-actions">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <el-button type="primary" @click="refreshData" :loading="loading" icon="Refresh">刷新</el-button>
        <el-button @click="exportReport" :loading="exporting" icon="Download">导出报表</el-button>
      </div>
    </div>

    <div class="report-content" v-loading="loading">
      <!-- 活动基本信息 -->
      <el-card class="info-card" v-if="eventData">
        <template #header>
          <div class="card-header with-border">
            <span>活动信息</span>
          </div>
        </template>
        <div class="event-info">
          <div class="info-item">
            <div class="label">活动名称</div>
            <div class="value">{{ eventData.eventTitle }}</div>
          </div>
          <div class="info-item">
            <div class="label">总票数</div>
            <div class="value">{{ eventData.totalTickets }}</div>
          </div>
          <div class="info-item">
            <div class="label">已售票数</div>
            <div class="value primary">{{ eventData.soldTickets }}</div>
          </div>
          <div class="info-item">
            <div class="label">剩余票数</div>
            <div class="value">{{ eventData.remainingTickets }}</div>
          </div>
          <div class="info-item">
            <div class="label">总收入</div>
            <div class="value success">¥{{ eventData.totalRevenue?.toFixed(2) || '0.00' }}</div>
          </div>
        </div>
      </el-card>

      <!-- 销售数据和图表 -->
      <div class="report-section">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>票种销售情况</span>
                </div>
              </template>
              <div class="chart-container" ref="ticketSalesChartRef"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>票种详情</span>
                </div>
              </template>
              <el-table :data="eventData?.ticketDetails || []" stripe style="width: 100%">
                <el-table-column prop="ticketName" label="票种名称" min-width="120" />
                <el-table-column prop="price" label="价格" min-width="100">
                  <template #default="scope">
                    ¥{{ scope.row.price?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
                <el-table-column prop="quantity" label="总数量" min-width="100" />
                <el-table-column prop="sold" label="已售数量" min-width="100" />
                <el-table-column prop="salesAmount" label="销售金额" min-width="120">
                  <template #default="scope">
                    ¥{{ scope.row.salesAmount?.toFixed(2) || '0.00' }}
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 销售趋势 -->
      <div class="report-section">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header with-actions">
              <span>销售趋势</span>
              <div class="chart-actions">
                <el-radio-group v-model="timeRange" size="small" @change="fetchSalesTrend">
                  <el-radio-button label="7d">最近7天</el-radio-button>
                  <el-radio-button label="30d">最近30天</el-radio-button>
                  <el-radio-button label="custom">自定义</el-radio-button>
                </el-radio-group>
                
                <el-date-picker
                  v-if="timeRange === 'custom'"
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="margin-left: 16px; width: 240px"
                  @change="handleDateRangeChange"
                />
              </div>
            </div>
          </template>
          <div class="trend-chart-container" ref="trendChartRef"></div>
          
          <div class="trend-summary" v-if="trendData">
            <div class="summary-item">
              <div class="label">总销售额</div>
              <div class="value">¥{{ trendData.totalSales?.toFixed(2) || '0.00' }}</div>
            </div>
            <div class="summary-item">
              <div class="label">日均销售</div>
              <div class="value">¥{{ trendData.averageDailySales?.toFixed(2) || '0.00' }}</div>
            </div>
            <div class="summary-item">
              <div class="label">峰值销售</div>
              <div class="value">¥{{ trendData.peakSales?.toFixed(2) || '0.00' }}</div>
            </div>
            <div class="summary-item">
              <div class="label">峰值时间</div>
              <div class="value">{{ trendData.peakTime || '-' }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 问卷反馈分析 -->
      <div class="report-section">
        <el-card shadow="hover" v-if="feedbackData?.questionStats?.length">
          <template #header>
            <div class="card-header">
              <span>问卷反馈分析</span>
              <el-tag type="success" v-if="feedbackData">
                总提交数: {{ feedbackData.totalResponses || 0 }}
              </el-tag>
            </div>
          </template>
          
          <el-collapse v-model="activeQuestion">
            <el-collapse-item v-for="(question, index) in feedbackData?.questionStats" :key="index" :name="index">
              <template #title>
                <div class="question-title">
                  <span class="question-index">Q{{ index + 1 }}</span>
                  <span>{{ question.questionText }}</span>
                  <span v-if="question.responseRate" class="question-rate">
                    {{ (question.responseRate * 100).toFixed(0) }}% 回答率
                  </span>
                </div>
              </template>
              
              <!-- 单选题和多选题 -->
              <div v-if="question.questionType === 'single' || question.questionType === 'multiple'">
                <div class="option-chart" :id="`option-chart-${index}`"></div>
                <el-table :data="question.options" style="width: 100%; margin-top: 20px">
                  <el-table-column prop="optionText" label="选项" min-width="200" />
                  <el-table-column prop="count" label="选择次数" width="100" />
                  <el-table-column prop="percentage" label="比例" width="100">
                    <template #default="scope">
                      {{ (scope.row.percentage * 100).toFixed(1) }}%
                    </template>
                  </el-table-column>
                  <el-table-column label="分布" min-width="200">
                    <template #default="scope">
                      <el-progress 
                        :percentage="scope.row.percentage * 100" 
                        :color="getRandomColor(index + scope.$index)"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 文本题 -->
              <div v-else-if="question.questionType === 'text'">
                <div class="text-analysis">
                  <div class="keyword-section">
                    <h4>关键词分析</h4>
                    <div class="keyword-cloud">
                      <el-tag 
                        v-for="(keyword, kwIndex) in question.keywords" 
                        :key="kwIndex"
                        :type="getTagType(kwIndex)"
                        style="margin: 5px"
                        :effect="kwIndex % 2 === 0 ? 'dark' : 'light'"
                      >
                        {{ keyword.word }} ({{ keyword.count }})
                      </el-tag>
                    </div>
                  </div>
                  
                  <div class="text-examples">
                    <h4>回答示例</h4>
                    <el-card v-for="(example, exIndex) in question.examples" :key="exIndex" class="example-card">
                      {{ example }}
                    </el-card>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
        
        <el-empty v-else description="该活动暂无问卷反馈数据" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { 
  getEventReport, 
  getEventSalesTrend, 
  getEventFeedbackReport 
} from '@/api/report'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import * as XLSX from 'xlsx'
import 'jspdf-autotable'

const route = useRoute()
const router = useRouter()
const eventId = ref(route.params.id)

// 状态变量
const loading = ref(false)
const exporting = ref(false)
const eventData = ref(null)
const trendData = ref(null)
const feedbackData = ref(null)

// 图表引用
const ticketSalesChartRef = ref(null)
const trendChartRef = ref(null)
let ticketSalesChart = null
let trendChart = null

// 销售趋势参数
const timeRange = ref('7d')
const dateRange = ref([])

// 问卷分析
const activeQuestion = ref([0]) // 默认展开第一个问题

// 初始化
onMounted(async () => {
  if (!eventId.value) {
    ElMessage.error('活动ID不能为空')
    goBack()
    return
  }
  
  await fetchEventData()
  await fetchSalesTrend()
  await fetchFeedbackData()
  
  window.addEventListener('resize', handleResize)
})

// 销毁前清理
const beforeUnmount = () => {
  window.removeEventListener('resize', handleResize)
  if (ticketSalesChart) ticketSalesChart.dispose()
  if (trendChart) trendChart.dispose()
  
  // 清理问题选项图表
  if (feedbackData.value && feedbackData.value.questionStats) {
    feedbackData.value.questionStats.forEach((_, index) => {
      const chart = echarts.getInstanceByDom(document.getElementById(`option-chart-${index}`))
      if (chart) chart.dispose()
    })
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (ticketSalesChart) ticketSalesChart.resize()
  if (trendChart) trendChart.resize()
  
  // 调整问题选项图表大小
  if (feedbackData.value && feedbackData.value.questionStats) {
    feedbackData.value.questionStats.forEach((_, index) => {
      const chart = echarts.getInstanceByDom(document.getElementById(`option-chart-${index}`))
      if (chart) chart.resize()
    })
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 获取活动数据
const fetchEventData = async () => {
  loading.value = true
  try {
    const res = await getEventReport(eventId.value)
    if (res.code === 200 && res.data) {
      eventData.value = res.data
      nextTick(() => {
        initTicketSalesChart()
      })
    } else {
      ElMessage.error(res.msg || '获取活动统计数据失败')
    }
  } catch (error) {
    console.error('获取活动统计数据出错:', error)
    ElMessage.error('获取活动统计数据失败')
  } finally {
    loading.value = false
  }
}

// 获取销售趋势
const fetchSalesTrend = async () => {
  loading.value = true
  try {
    const params = {
      range: timeRange.value
    }
    
    if (timeRange.value === 'custom' && dateRange.value?.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    const res = await getEventSalesTrend(eventId.value, params)
    if (res.code === 200 && res.data) {
      trendData.value = res.data
      nextTick(() => {
        initTrendChart()
      })
    } else {
      ElMessage.error(res.msg || '获取销售趋势数据失败')
    }
  } catch (error) {
    console.error('获取销售趋势数据出错:', error)
    ElMessage.error('获取销售趋势数据失败')
  } finally {
    loading.value = false
  }
}

// 获取问卷反馈数据
const fetchFeedbackData = async () => {
  loading.value = true
  try {
    const res = await getEventFeedbackReport(eventId.value)
    if (res.code === 200 && res.data) {
      feedbackData.value = res.data
      nextTick(() => {
        initQuestionOptionCharts()
      })
    } else {
      console.error('获取问卷反馈数据失败:', res.msg)
    }
  } catch (error) {
    console.error('获取问卷反馈数据出错:', error)
  } finally {
    loading.value = false
  }
}

// 初始化票种销售图表
const initTicketSalesChart = () => {
  if (!ticketSalesChartRef.value || !eventData.value) return
  
  ticketSalesChart = echarts.init(ticketSalesChartRef.value)
  
  const data = eventData.value.ticketDetails.map(ticket => ({
    name: ticket.ticketName,
    value: ticket.sold
  }))
  
  ticketSalesChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '票种销售',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  })
}

// 初始化销售趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value || !trendData.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const xAxisData = trendData.value.dataPoints.map(point => point.date)
  const seriesData = trendData.value.dataPoints.map(point => point.amount)
  
  trendChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        return `${params[0].name}<br/>销售额: ¥${params[0].value.toFixed(2)}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [{
      data: seriesData,
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      }
    }]
  })
  
  // 设置图表高度
  trendChartRef.value.style.height = '350px'
  trendChart.resize()
}

// 初始化问题选项图表
const initQuestionOptionCharts = () => {
  if (!feedbackData.value || !feedbackData.value.questionStats) return
  
  // 处理每个问题的图表
  feedbackData.value.questionStats.forEach((question, index) => {
    if (question.questionType !== 'text') {
      nextTick(() => {
        const chartElement = document.getElementById(`option-chart-${index}`)
        if (!chartElement) return
        
        const optionChart = echarts.init(chartElement)
        const optionsData = question.options.map(option => ({
          name: option.optionText,
          value: option.count
        }))
        
        optionChart.setOption({
          tooltip: {
            trigger: 'item'
          },
          legend: {
            top: '5%',
            left: 'center'
          },
          series: [
            {
              name: '选择次数',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              data: optionsData
            }
          ]
        })
        
        // 设置图表高度
        chartElement.style.height = '300px'
        optionChart.resize()
      })
    }
  })
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    fetchSalesTrend()
  }
}

// 刷新数据
const refreshData = async () => {
  await fetchEventData()
  await fetchSalesTrend()
  await fetchFeedbackData()
}

// 导出报表
const exportReport = () => {
  if (exporting.value) return
  exporting.value = true
  
  ElMessage.info('正在生成PDF文件，请稍候...')
  
  // 创建一个临时容器用于渲染报表内容
  const element = document.createElement('div')
  element.style.width = '100%'
  element.style.padding = '20px'
  element.style.backgroundColor = '#ffffff'
  element.style.position = 'absolute'
  element.style.left = '-9999px'
  element.style.top = '-9999px'
  document.body.appendChild(element)
  
  // 添加报表标题
  const titleDiv = document.createElement('div')
  titleDiv.style.textAlign = 'center'
  titleDiv.style.marginBottom = '20px'
  titleDiv.innerHTML = `
    <h1 style="font-size: 24px; color: #333;">${eventData.value?.eventTitle || '活动'} - 活动统计报表</h1>
    <p style="color: #666; font-size: 14px;">导出时间: ${new Date().toLocaleString()}</p>
  `
  element.appendChild(titleDiv)
  
  // 添加活动基本信息
  const infoDiv = document.createElement('div')
  infoDiv.style.marginBottom = '30px'
  infoDiv.style.borderRadius = '5px'
  infoDiv.style.padding = '15px'
  infoDiv.style.backgroundColor = '#f8f9fa'
  infoDiv.style.border = '1px solid #eee'
  
  infoDiv.innerHTML = `
    <h2 style="font-size: 18px; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;">活动基本信息</h2>
    <div style="display: flex; flex-wrap: wrap;">
      <div style="min-width: 200px; margin-bottom: 15px; flex: 1;">
        <div style="font-size: 14px; color: #666; margin-bottom: 5px;">活动名称</div>
        <div style="font-size: 16px; font-weight: bold;">${eventData.value?.eventTitle || '-'}</div>
      </div>
      <div style="min-width: 150px; margin-bottom: 15px; flex: 1;">
        <div style="font-size: 14px; color: #666; margin-bottom: 5px;">总票数</div>
        <div style="font-size: 16px; font-weight: bold;">${eventData.value?.totalTickets || 0}</div>
      </div>
      <div style="min-width: 150px; margin-bottom: 15px; flex: 1;">
        <div style="font-size: 14px; color: #666; margin-bottom: 5px;">已售票数</div>
        <div style="font-size: 16px; font-weight: bold; color: #5470c6;">${eventData.value?.soldTickets || 0}</div>
      </div>
      <div style="min-width: 150px; margin-bottom: 15px; flex: 1;">
        <div style="font-size: 14px; color: #666; margin-bottom: 5px;">剩余票数</div>
        <div style="font-size: 16px; font-weight: bold;">${eventData.value?.remainingTickets || 0}</div>
      </div>
      <div style="min-width: 150px; margin-bottom: 15px; flex: 1;">
        <div style="font-size: 14px; color: #666; margin-bottom: 5px;">总收入</div>
        <div style="font-size: 16px; font-weight: bold; color: #91cc75;">¥${(eventData.value?.totalRevenue || 0).toFixed(2)}</div>
      </div>
    </div>
  `
  element.appendChild(infoDiv)

  // 添加票种销售情况表格
  if (eventData.value?.ticketTypes && eventData.value.ticketTypes.length > 0) {
    const ticketsDiv = document.createElement('div')
    ticketsDiv.style.marginBottom = '30px'
    
    let ticketsHtml = `
      <h2 style="font-size: 18px; margin-bottom: 15px;">票种销售情况</h2>
      <table style="width: 100%; border-collapse: collapse; border: 1px solid #eee;">
        <thead>
          <tr style="background-color: #f8f9fa;">
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">票种名称</th>
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">价格 (¥)</th>
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">总票数</th>
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">已售</th>
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">剩余</th>
            <th style="padding: 10px; text-align: left; border: 1px solid #eee;">销售额 (¥)</th>
          </tr>
        </thead>
        <tbody>
    `
    
    eventData.value.ticketTypes.forEach(ticket => {
      ticketsHtml += `
        <tr>
          <td style="padding: 10px; border: 1px solid #eee;">${ticket.name}</td>
          <td style="padding: 10px; border: 1px solid #eee;">${ticket.price.toFixed(2)}</td>
          <td style="padding: 10px; border: 1px solid #eee;">${ticket.total}</td>
          <td style="padding: 10px; border: 1px solid #eee;">${ticket.sold}</td>
          <td style="padding: 10px; border: 1px solid #eee;">${ticket.remaining}</td>
          <td style="padding: 10px; border: 1px solid #eee;">${(ticket.price * ticket.sold).toFixed(2)}</td>
        </tr>
      `
    })
    
    ticketsHtml += `
        </tbody>
      </table>
    `
    
    ticketsDiv.innerHTML = ticketsHtml
    element.appendChild(ticketsDiv)
  }
  
  // 添加问卷统计数据（如果有）
  if (feedbackData.value?.questions && feedbackData.value.questions.length > 0) {
    const feedbackDiv = document.createElement('div')
    feedbackDiv.style.marginBottom = '30px'
    
    let feedbackHtml = `
      <h2 style="font-size: 18px; margin-bottom: 15px;">问卷反馈分析</h2>
      <p style="margin-bottom: 15px;">问卷填写人数: ${feedbackData.value.totalResponses || 0} 人</p>
    `
    
    feedbackData.value.questions.forEach((question, index) => {
      feedbackHtml += `
        <div style="margin-bottom: 20px; padding: 15px; border: 1px solid #eee; border-radius: 5px;">
          <h3 style="margin-bottom: 10px; font-size: 16px;">
            <span style="display: inline-block; width: 25px; height: 25px; background-color: #5470c6; color: white; text-align: center; line-height: 25px; border-radius: 50%; margin-right: 10px;">${index + 1}</span>
            ${question.title}
            <span style="float: right; color: #909399; font-size: 13px; font-weight: normal;">
              回答率: ${question.responseRate}%
            </span>
          </h3>
          
          <div>
            <ul style="list-style: none; padding: 0; margin: 0;">
      `
      
      question.options.forEach(option => {
        feedbackHtml += `
              <li style="margin-bottom: 10px;">
                <div style="display: flex; align-items: center;">
                  <span style="flex: 1; margin-right: 10px;">${option.text}</span>
                  <span style="width: 50px; text-align: right;">${option.percentage}%</span>
                  <span style="width: 100px; margin-left: 10px;">
                    <div style="background-color: #f5f7fa; height: 20px; width: 100%; border-radius: 3px;">
                      <div style="background-color: #5470c6; height: 20px; width: ${option.percentage}%; border-radius: 3px;"></div>
                    </div>
                  </span>
                </div>
              </li>
        `
      })
      
      feedbackHtml += `
            </ul>
          </div>
        </div>
      `
    })
    
    feedbackDiv.innerHTML = feedbackHtml
    element.appendChild(feedbackDiv)
  }
  
  // 添加页脚
  const footerDiv = document.createElement('div')
  footerDiv.innerHTML = `
    <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">
    <p style="text-align: center; color: #999; font-size: 12px;">© ${new Date().getFullYear()} 活动管理系统 - 活动统计报表</p>
  `
  
  element.appendChild(footerDiv)
  
  // 使用html2canvas和jsPDF
  setTimeout(() => {
    html2canvas(element, {
      scale: 2,
      useCORS: true,
      logging: false,
      allowTaint: true,
      backgroundColor: '#FFFFFF'
    }).then(canvas => {
      // 删除临时元素
      document.body.removeChild(element)
      
      const imgData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = new jsPDF('p', 'mm', 'a4')
      const pdfWidth = pdf.internal.pageSize.getWidth()
      const pdfHeight = pdf.internal.pageSize.getHeight()
      const imgWidth = canvas.width
      const imgHeight = canvas.height
      const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight)
      const imgX = (pdfWidth - imgWidth * ratio) / 2
      const imgY = 0
      
      pdf.addImage(imgData, 'JPEG', imgX, imgY, imgWidth * ratio, imgHeight * ratio)
      pdf.save(`${eventData.value?.eventTitle || '活动'}_统计报表_${new Date().toISOString().split('T')[0]}.pdf`)
      
      exporting.value = false
      ElMessage.success('PDF导出成功')
    }).catch(error => {
      console.error('PDF导出失败:', error)
      document.body.removeChild(element)
      exporting.value = false
      ElMessage.error('PDF导出失败')
    })
  }, 1000) // 给足够时间让内容渲染完成
}

// 实现Excel导出功能
const exportAsExcel = () => {
  if (exporting.value) return
  exporting.value = true
  
  ElMessage.info('正在生成Excel文件，请稍候...')
  
  try {
    // 准备数据
    const workbook = XLSX.utils.book_new()
    
    // 添加文档属性
    workbook.Props = {
      Title: `${eventData.value?.eventTitle || '活动'} - 统计报表`,
      Subject: "活动管理系统数据报表",
      Author: "活动管理系统",
      CreatedDate: new Date()
    }
    
    // 1. 创建活动信息工作表
    const eventInfoData = [
      [`${eventData.value?.eventTitle || '活动'} - 统计报表`, ''],
      ['导出时间', new Date().toLocaleString()],
      [''],
      ['活动基本信息', ''],
      ['指标', '数值', '说明'],
      ['活动名称', eventData.value?.eventTitle || '-', ''],
      ['总票数', eventData.value?.totalTickets || 0, '活动的票种总数量'],
      ['已售票数', eventData.value?.soldTickets || 0, '已售出的票数量'],
      ['剩余票数', eventData.value?.remainingTickets || 0, '剩余可售的票数量'],
      ['总收入', `¥${(eventData.value?.totalRevenue || 0).toFixed(2)}`, '票务销售总金额'],
      ['售出比例', `${eventData.value ? ((eventData.value.soldTickets / eventData.value.totalTickets) * 100).toFixed(2) : 0}%`, '已售出票数占总票数的百分比'],
      ['']
    ]
    
    // 如果有票种数据，添加到表格
    if (eventData.value?.ticketTypes && eventData.value.ticketTypes.length > 0) {
      eventInfoData.push(['票种销售情况', '', '', '', '', ''])
      eventInfoData.push(['票种名称', '价格(¥)', '总票数', '已售', '剩余', '销售额(¥)'])
      
      eventData.value.ticketTypes.forEach(ticket => {
        eventInfoData.push([
          ticket.name,
          ticket.price.toFixed(2),
          ticket.total,
          ticket.sold,
          ticket.remaining,
          (ticket.price * ticket.sold).toFixed(2)
        ])
      })
      
      eventInfoData.push([''])
    }
    
    const eventInfoSheet = XLSX.utils.aoa_to_sheet(eventInfoData)
    
    // 设置列宽
    eventInfoSheet['!cols'] = [
      { wch: 20 }, // A列宽
      { wch: 15 }, // B列宽
      { wch: 20 }, // C列宽
      { wch: 15 }, // D列宽
      { wch: 15 }, // E列宽
      { wch: 15 }  // F列宽
    ]
    
    // 合并单元格
    eventInfoSheet['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: 5 } }, // 合并标题行
      { s: { r: 3, c: 0 }, e: { r: 3, c: 5 } } // 合并"活动基本信息"行
    ]
    
    // 如果有票种数据，合并票种销售情况标题
    if (eventData.value?.ticketTypes && eventData.value.ticketTypes.length > 0) {
      const baseRow = 12 // 基本信息之后的行
      eventInfoSheet['!merges'].push({ s: { r: baseRow, c: 0 }, e: { r: baseRow, c: 5 } }) // 合并"票种销售情况"行
    }
    
    XLSX.utils.book_append_sheet(workbook, eventInfoSheet, '活动信息')
    
    // 2. 如果有问卷数据，创建问卷反馈工作表
    if (feedbackData.value?.questions && feedbackData.value.questions.length > 0) {
      const feedbackData = [
        ['问卷反馈分析', ''],
        ['问卷填写人数', feedbackData.value.totalResponses || 0],
        ['']
      ]
      
      feedbackData.value.questions.forEach((question, qIndex) => {
        feedbackData.push([`问题 ${qIndex + 1}: ${question.title}`, `回答率: ${question.responseRate}%`])
        feedbackData.push(['选项', '人数', '百分比'])
        
        question.options.forEach(option => {
          feedbackData.push([
            option.text,
            option.count,
            `${option.percentage}%`
          ])
        })
        
        feedbackData.push(['']) // 添加空行分隔问题
      })
      
      const feedbackSheet = XLSX.utils.aoa_to_sheet(feedbackData)
      
      // 设置列宽
      feedbackSheet['!cols'] = [
        { wch: 40 }, // A列宽
        { wch: 15 }, // B列宽
        { wch: 15 }  // C列宽
      ]
      
      // 合并单元格
      const merges = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 2 } } // 合并标题行
      ]
      
      // 合并每个问题的标题行
      let rowIndex = 3
      feedbackData.value.questions.forEach(question => {
        merges.push({ s: { r: rowIndex, c: 0 }, e: { r: rowIndex, c: 2 } })
        rowIndex += question.options.length + 2 // 标题行 + 选项行 + 表头行 + 空行
      })
      
      feedbackSheet['!merges'] = merges
      
      XLSX.utils.book_append_sheet(workbook, feedbackSheet, '问卷反馈')
    }
    
    // 导出Excel文件
    XLSX.writeFile(workbook, `${eventData.value?.eventTitle || '活动'}_统计报表_${new Date().toISOString().split('T')[0]}.xlsx`)
    
    exporting.value = false
    ElMessage.success('Excel导出成功')
  } catch (error) {
    console.error('Excel导出失败:', error)
    exporting.value = false
    ElMessage.error('Excel导出失败')
  }
}

// 获取标签类型
const getTagType = (index) => {
  const types = ['', 'success', 'warning', 'danger', 'info']
  return types[index % types.length]
}

// 获取随机颜色
const getRandomColor = (seed) => {
  const colors = [
    '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
    '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'
  ]
  return colors[seed % colors.length]
}
</script>

<style scoped>
.event-report-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #7a75e3);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.report-content {
  margin-bottom: 20px;
}

.report-section {
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.event-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: space-between;
}

.info-item {
  min-width: 150px;
  flex: 1;
}

.label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.value {
  font-size: 20px;
  font-weight: bold;
}

.value.primary {
  color: var(--primary-color);
}

.value.success {
  color: var(--success-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header.with-border {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.card-header.with-actions {
  flex-direction: column;
  align-items: flex-start;
}

.chart-actions {
  margin-top: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.trend-chart-container {
  height: 350px;
  width: 100%;
}

.trend-summary {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 20px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.summary-item {
  flex: 1;
  min-width: 150px;
  text-align: center;
  padding: 10px;
}

.question-title {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.question-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 25px;
  height: 25px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 50%;
  font-size: 12px;
  margin-right: 10px;
}

.question-rate {
  margin-left: auto;
  color: #909399;
  font-size: 13px;
  font-weight: normal;
}

.option-chart {
  height: 300px;
  width: 100%;
}

.text-analysis {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.keyword-section, .text-examples {
  margin-bottom: 20px;
}

.keyword-section h4, .text-examples h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #606266;
  font-size: 16px;
}

.keyword-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.example-card {
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 16px;
    width: 100%;
    flex-wrap: wrap;
  }
  
  .event-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .chart-actions {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .el-date-picker {
    width: 100% !important;
    margin-left: 0 !important;
    margin-top: 10px;
  }
  
  .trend-summary {
    flex-direction: column;
  }
  
  .summary-item {
    border-bottom: 1px dashed #ddd;
    padding: 10px 0;
  }
  
  .summary-item:last-child {
    border-bottom: none;
  }
}

.header-actions :deep(.el-button--primary) {
  background: #5e5ce6;
  border-color: #5e5ce6;
}

.header-actions :deep(.el-button--primary:hover) {
  background: #6b69e3;
  border-color: #6b69e3;
}
</style> 